<template>
  <div>
    <div v-show="showCer" @click.stop="closeCertificate" :class="[matchPaper&&matchPaper.shapeType==2?'c-ph40':'c-ph100','c-translucent-balck80 c-pz1000 c-pf c-flex-column c-p-t0 c-flex-center c-h c-w100 c-maxw640']">
      <img class="c-w100" id="spreadClockImg" src="" alt="">
      <div class="c-fs24 c-fc-white c-textAlign-c c-mt16 ">长按保存图片，分享给好友</div>
    </div>
    <div class="canvasBox c-flex-row" v-if="matchPaper.certificateType==1&&matchPaper.shapeType==1">
      <div class="anvasContent c-p" id="examcanvas1">
        <img :src="$addXossFilter(spreadInfo.bgImgUrl)" alt class="c-w100 c-h img-pe-none">
        <div class="customOne bgLocation">
          <div style="font-size: 60px;color: #333333;font-weight: 600;padding-top: 180px;" class="c-textAlign-c">{{spreadInfo.title}}</div>
          <div style="margin:30px auto 0;">
            <div class="c-flex-column c-aligni-center c-justify-center">
              <div class="c-brp50 c-text-hidden" style="width:130px;height:130px;" :class="matchPaper.enableAvatarShow==0?'c-opacity0':''">
                <img :src="$addXossFilter(spreadInfo.headimgurl, require('@/assets/defult_head.png'))" alt class="c-w100 c-h img-pe-none">
              </div>
              <div class=" c-fw-b c-textAlign-c" style="height:38px;font-size:36px;margin-top:24px;">{{matchPaper.nameTypeShow == 0?'':matchPaper.nameTypeShow == 1 ? spreadInfo.nickname : (spreadInfo.realName == '' ? spreadInfo.nickname : spreadInfo.realName)}}</div>
            </div>
          </div>
          <div class="c-fc-xblack c-textAlign-c" style="font-size: 30px;margin-top: 20px;" v-for="(item,index) in spreadInfo.name" :key="index">{{ item }}</div>
          <div v-if="matchPaper.prodType!=77" class="c-flex-row c-aligni-center c-textAlign-c c-justify-center c-fc-sblack" style="margin-top:64px;font-size: 24px;">
            <div v-for="(item,index) in matchPaper.defineShowContent" :key="index" style="color: #C87F1B;">
              <div v-if="item==5" style="margin:0 18px;">
                <div class="c-fw-b" style="font-size: 50px;">{{matchPaper.paperBaseInfo.totalpoins}}</div>
                <div style="margin-top:24px;font-size: 30px;">分数</div>
              </div>
              <div v-if="item==6" style="margin:0 18px;">
                <div class="c-fw-b" style="font-size: 50px;">{{Number(matchPaper.paperBaseInfo.accuracy * 100).toFixed(0) + '%'}}</div>
                <div style="margin-top:24px;font-size: 30px;">正确率</div>
              </div>
              <div v-if="item==7" style="margin:0 18px;">
                <div class="c-fw-b" style="font-size: 50px;">{{matchPaper.paperBaseInfo.rightNum}}</div>
                <div style="margin-top:24px;font-size: 30px;">正确题数</div>
              </div>
            </div>
          </div>
          <div v-else class="c-flex-row c-aligni-center c-textAlign-c c-justify-center c-fc-sblack" style="margin-top:64px;">
            <div v-for="(item,index) in matchPaper.defineShowContent" :key="index">
              <div v-if="item==5" style="margin:0 18px;">
                <div class="c-fw-b c-fc-xxmred" style="font-size: 60px;">{{matchPaper.paperBaseInfo.totalpoins}}分</div>
              </div>
            </div>
          </div>
          <div style="margin-top:64px;">
            <div class="c-textAlign-c c-fc-sblack" style="font-size: 24px;margin-bottom:20px;" v-for="(item,index) in spreadInfo.wordArr" :key="index">{{ item }}</div>
          </div>
          <div class="c-w100">
            <div class="c-flex-row c-aligni-center" style="width: 600px;margin: 0 auto;margin-top: 80px;">
              <div :class="spreadInfo.enableShowQrCode == 0||
                (spreadInfo.enableInstitution == 0&&spreadInfo.enableGrantTime == 0&&spreadInfo.enableNumber == 0&&spreadInfo.enableStamp==0)?'c-justify-center':'c-justify-sb'" style="width:540px;margin:auto" class="c-flex-row">
                <div v-if="spreadInfo.enableShowQrCode==1" class="c-flex-column c-aligni-center c-textAlign-c c-justify-center">
                  <img :src="$addXossFilter(spreadInfo.qrcodeUrl)" alt class="img-pe-none" style="width:140px;height:140px">
                  <div class="c-textAlign-c c-fc-sblack" v-if="spreadInfo.enableShowQrCode==1" style="width:170px;font-size:20px;margin-top:12px">{{spreadInfo.qrCodeText}}</div>
                </div>
                <div style="width: 300px;" v-if="!(spreadInfo.enableInstitution == 0&&spreadInfo.enableGrantTime == 0&&spreadInfo.enableNumber == 0&&spreadInfo.enableStamp==0)" class="c-flex-column c-p">
                  <div v-if="spreadInfo.enableStamp!=0" style="width: 120px;height: 120px;margin: 0 auto;position: absolute;left: 0;
                right: 0;top: 0;bottom: 0;margin: 0 auto;"><img :src="spreadInfo.enableStamp==2?spreadInfo.stampImg:spreadInfo.backdropId==3?require('@/assets/i/wap/camp/pass2.png'):require('@/assets/i/wap/camp/pass.png')" alt=""></div>
                  <div style="font-size: 22px;color: #333333;width: 300px;" v-if="spreadInfo.enableInstitution == 1">{{spreadInfo.institutionName}}</div>
                  <div style="font-size: 20px;color: #666;margin-top: 14px;" v-if="spreadInfo.enableGrantTime == 1">发证日期：{{ spreadInfo.createdAt }}</div>
                  <div style="font-size: 20px;color: #666;margin-top: 8px;width: 300px;word-break: break-all;" v-if="spreadInfo.enableNumber&&spreadInfo.number">证书编号：{{spreadInfo.number}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="canvasBoxhor c-flex-row" v-if="matchPaper.certificateType == 1&&matchPaper.shapeType==2">
      <div class="anvasContenthor c-p" id="examcanvas3">
        <img :src="$addXossFilter(spreadInfo.bgImgUrl)" alt class="c-w100 c-h img-pe-none">
        <div class="customOne bgLocation">
          <div style="font-size: 22px;color: #333333;font-weight: 600;padding-top: 46px;" class="c-textAlign-c">{{spreadInfo.title}}</div>
          <div style="margin:32px auto 0;">
            <div class="c-flex-column c-aligni-center c-justify-center">
              <div class="c-brp50 c-text-hidden" style="width:50px;height:50px;" :class="matchPaper.enableAvatarShow==0?'c-opacity0':''">
                <img :src="$addXossFilter(spreadInfo.headimgurl, require('@/assets/defult_head.png'))" alt class="c-w100 c-h img-pe-none">
              </div>
              <div class=" c-fw-b c-textAlign-c" style="height:24px;font-size:16px;margin-top:4px;">{{matchPaper.nameTypeShow == 0?'':matchPaper.nameTypeShow == 1 ? spreadInfo.nickname : (spreadInfo.realName == '' ? spreadInfo.nickname : spreadInfo.realName)}}</div>
            </div>
            <div class="c-textAlign-c c-fw-b c-fc-xblack" style="margin-top: 4px; font-size: 14px;height: 20px;">
              <div v-for="(item,index) in spreadInfo.name" :key="index">{{ item }}</div>
            </div>
            <div v-if="matchPaper.prodType!=77" class="c-flex-row c-aligni-center c-textAlign-c c-justify-center c-fc-sblack" style="margin-top:30px;font-size: 24px;">
              <div v-for="(item,index) in matchPaper.defineShowContent" :key="index" style="color: #C87F1B;">
                <div v-if="item==5" style="margin:0 18px;">
                  <div class="c-fw-b c-fc-xblack" style="font-size: 24px;">{{matchPaper.paperBaseInfo.totalpoins}}</div>
                  <div class="c-fc-gray" style="margin-top:6px;font-size: 18px;">分数</div>
                </div>
                <div v-if="item==6" style="margin:0 18px;">
                  <div class="c-fw-b c-fc-xblack" style="font-size: 24px;">{{Number(matchPaper.paperBaseInfo.accuracy * 100).toFixed(0) + '%'}}</div>
                  <div class="c-fc-gray" style="margin-top:6px;font-size: 18px;">正确率</div>
                </div>
                <div v-if="item==7" style="margin:0 18px;">
                  <div class="c-fw-b c-fc-xblack" style="font-size: 24px;">{{matchPaper.paperBaseInfo.rightNum}}</div>
                  <div class="c-fc-gray" style="margin-top:6px;font-size: 18px;">正确题数</div>
                </div>
              </div>
            </div>
            <div v-else class="c-flex-row c-aligni-center c-textAlign-c c-justify-center c-fc-sblack" style="margin-top:26px;font-size: 24px;">
              <div v-for="(item,index) in matchPaper.defineShowContent" :key="index" style="color: #D60808;">
                <div v-if="item==5" style="margin:0 18px;">
                  <div class="c-fw-b" style="font-size: 36px;">{{matchPaper.paperBaseInfo.totalpoins}}分</div>
                </div>
              </div>
            </div>
          </div>
          <div class="c-textAlign-c c-fc-xblack" style="margin-top: 14px; font-size: 18px;">
            <div style="margin-bottom: 6px;" v-for="(item,index) in spreadInfo.wordArr" :key="index">{{ item }}</div>
          </div>
          <div class="c-pa c-w100" style="top: 400px;">
            <div class="c-flex-row c-aligni-center" style="width: 600px;margin: 0 auto;">
              <div style="width:600px;margin:auto" class="c-flex-row c-aligni-center c-justify-sb">
                <div>
                  <div v-if="spreadInfo.enableShowQrCode==1" class="c-flex-row c-aligni-center c-justify-center">
                    <img :src="$addXossFilter(spreadInfo.qrcodeUrl)" alt class="img-pe-none" style="width:76px;height:76px">
                    <div class="c-textAlign-l" v-if="spreadInfo.enableShowQrCode==1" style="width:160px;font-size:16px;margin-left: 10px;color: #666;">{{spreadInfo.qrCodeText}}</div>
                  </div>
                </div>
                <div>
                  <div v-if="!(spreadInfo.enableInstitution == 0&&spreadInfo.enableGrantTime == 0&&spreadInfo.enableNumber == 0&&spreadInfo.enableStamp==0)" class="c-flex-column c-p c-textAlign-r">
                    <div v-if="spreadInfo.enableStamp!=0" style="width: 96px;height: 96px;margin: 0 auto;position: absolute;left: 0;
                right: 0;top: 0;bottom: 0;margin: 0 auto;"><img :src="spreadInfo.enableStamp==2?spreadInfo.stampImg:require('@/assets/i/wap/camp/pass.png')" alt=""></div>
                    <div style="font-size: 16px;color: #333333;" v-if="spreadInfo.enableInstitution == 1">{{spreadInfo.institutionName}}</div>
                    <div style="font-size: 16px;color: #666;margin-top: 8px;" v-if="spreadInfo.enableGrantTime == 1">发证日期：{{ spreadInfo.createdAt }}</div>
                    <div style="font-size: 16px;color: #666;margin-top: 8px;word-break: break-all;" v-if="spreadInfo.enableNumber&&spreadInfo.number">证书编号：{{spreadInfo.number}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="c-flex-row" :class="matchPaper.shapeType==1?'canvasBox':'shapecanvasBoxhor'" v-if="matchPaper.certificateType==2">
      <div class="c-p" :class="matchPaper.shapeType==1?'anvasContent':'shapeanvasContenthor'" id="examcanvas2">
        <img :src="$addXossFilter(matchPaper.customizeImage)" alt class="c-w100 c-h img-pe-none">
        <div v-if="matchPaper.customizeControl" class="customOne bgLocation">
          <div v-for="(item,index) in matchPaper.customizeControl" :key="index">
            <div v-if="item.type==3" :style="item" class="c-pa">
              <div class="c-flex-column c-aligni-center">
                <img :src="$addXossFilter(matchPaper.headimgurl)" alt class="headerImg120 c-brp50 img-pe-none">
                <p>{{matchPaper.nickname}}</p>
              </div>
            </div>
            <div v-if="item.type==2" :style="item" class="c-pa c-table">
              <span class="c-tableCell" :style="'vertical-align:'+item.verticalAlign">{{item.name}}</span>
            </div>
            <img v-if="item.type==1" class="c-pa" :src="$addXossFilter(matchPaper.paperBaseInfo.qrCodeUrl)" alt :style="item">
            <div v-if="item.type==6" :style="item" class="c-pa">
              <div class="c-flex-column c-aligni-center">
                <img style="width:92px;height:92px;" :src="$addXossFilter(matchPaper.headimgurl || require('@/assets/defult_head.png'))" alt class="headerImg120 c-brp50 img-pe-none">
              </div>
            </div>
            <div v-if="item.type==7" :style="item" class="c-pa c-table">
              <span class="c-tableCell" :style="'verticalAlign:'+item.verticalAlign">
                {{item.nameTypeShow==2&&matchPaper.realName?matchPaper.realName:matchPaper.nickname}}
              </span>
            </div>
            <img v-if="item.type==8" class="c-pa" :src="$addXossFilter(item.img, require('@/assets/defult270.png'))" alt :style="item">
            <div v-if="item.type==9" :style="item" class="c-pa c-table">
              <span class="c-tableCell" :style="'verticalAlign:'+item.verticalAlign">
                {{item.name}}
              </span>
            </div>
            <div v-if="item.type==10&&matchPaper.number" :style="item" class="c-pa c-table">
              <span class="c-tableCell" :style="'word-break: break-all;verticalAlign:'+item.verticalAlign">
                证书编号：{{matchPaper.number}}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { utilJs } from "@/utils/common.js"
const CANVAS_WIDTH = 750;
const CANVAS_HEIGHT = 1334;
let html2canvas = null;
let imgData = {};
export default {
  name: "examinationCer",
  components: {
  },
  props: {
    testRes: {
      type: Object,
      default: null,
    },
    bigType: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      showCer: false,
      isDrawing: false,
      matchPaper:'',
      spreadInfo:{},
      prodType:'',
      prodId:'',
      topicId:'',
      time:new Date().getTime()
    };
  },
  mounted() {
    import(/* webpackChunkName: "html2canvas" */"@/utils/html2canvas.js").then(res => {
      html2canvas = res.default;
    })
    utilJs.getAliSign(`${global.apiurl}imageSign`, (res) => {
      imgData = res;
    });
  },
  computed: {
  },
  methods: {
    closeCertificate() {
      this.showCer = false
      let ig = document.getElementById("spreadClockImg");
          ig.setAttribute("src", '');
    },
    canvas() {
      let domTest = this.matchPaper.certificateType == 1 && this.matchPaper.shapeType == 1 ? document.getElementById("examcanvas1") :
      this.matchPaper.certificateType == 1 && this.matchPaper.shapeType == 2 ? document.getElementById("examcanvas3") :
      document.getElementById("examcanvas2");
      if (!domTest) {
        return;
      }
      html2canvas(domTest, {
        useCORS: true,
        height: domTest.offsetHeight, // 解决当前页面生成图片出现白边问题
        width: domTest.offsetWidth,
      }).then(canvas => {// eslint-disable-line
        // document.body.appendChild(canvas);
        let ctx = canvas.getContext("2d");
        this.canvasToImage(ctx);
      });
    },
    drawNow(topicId, prodId, prodType) {
      let $this = this;
      this.prodType = prodType,
      this.prodId = prodId
      this.topicId = topicId
      this.time = new Date().getTime()
      this.$loading.show({
        text: "证书生成中"
      });
      if (this.isDrawing == true) {
        return;
      }
      this.isDrawing = true;
      utilJs.getMethod(global.apiurl + 'Certificate/cardShow?prodType=' + $this.prodType + "&prodId=" + $this.prodId + "&fromTopicId=" + $this.topicId + '&type=1', function (res) {
        $this.showCer = true;
        if ($this.prodType == global.ckFrom.voiceTest) {
          res.paperBaseInfo = res.aiBaseInfo
        }
        $this.matchPaper = res
        $this.isDrawing = false;
        if (res.certificateType == 2) {
          if ($this.matchPaper.customizeControl) {
            for (let i = 0; i < $this.matchPaper.customizeControl.length; i++) {
              $this.matchPaper.customizeControl[i].height = $this.matchPaper.customizeControl[i].height * 2 + 'px'
              $this.matchPaper.customizeControl[i].width = $this.matchPaper.customizeControl[i].width * 2 + 'px'
              $this.matchPaper.customizeControl[i].lineHeight = $this.matchPaper.customizeControl[i].lineHeight * 2 + 'px'
              $this.matchPaper.customizeControl[i].left = $this.matchPaper.customizeControl[i].posX * 2 + 'px'
              $this.matchPaper.customizeControl[i].top = $this.matchPaper.customizeControl[i].posY * 2 + 'px'
              $this.matchPaper.customizeControl[i].fontSize = $this.matchPaper.customizeControl[i].size * 2 + 'px'
              $this.matchPaper.customizeControl[i].letterSpacing = $this.matchPaper.customizeControl[i].letterSpacing * 2 + 'px'
            }
          }
        } else {
          let titleT = res.prodName;
          let titleArr = [];
          if ($this.matchPaper.shapeType == 2) {
            titleT = "在【" + res.prodName;
            if (titleT.length > 32) {
              let title1 = titleT.substring(0, 32);
              titleArr.push(title1);
              let title2 = "";
              title2 = titleT.substring(32, 50);
              title2 = res.paperBaseInfo.scoringMethod == 3 ? title2 + "】中答对" : title2 + '】中取得' ;
              titleArr.push(title2);
            } else {
              let title1 = res.paperBaseInfo.scoringMethod == 3 ? titleT.substring(0, 32) + "】中答对" : titleT.substring(0, 32) + '】中取得';
              titleArr.push(title1);
            }
          } else {
            if (titleT.length > 0 && titleT.length <= 16) {
              let title1 = res.paperBaseInfo.scoringMethod == 3 ? ('在【' + res.prodName + '】中答对') : ('在【' + res.prodName + '】中取得');
              titleArr.push(title1);
            } else if (titleT.length > 16) {
              let title1 = '在【' + titleT.substring(0, 16);
              let title2 = "";
              if (titleT.length <= 32) {
                title2 = titleT.substring(16, 32);
                title2 = res.paperBaseInfo.scoringMethod == 3 ? (title2 + '】中答对') : (title2 + '】中取得');
              } else {
                title2 = titleT.substring(16, 32);
                title2 = res.paperBaseInfo.scoringMethod == 3 ? (title2 + '...】中答对') : (title2 + '...】中取得') ;
              }
              titleArr.push(title1);
              titleArr.push(title2);
            }
          }
          let qrcodeUrl = "";
          let qrCodeText = "长按识别图中二维码，查看测试"
          if (res.redirectTo == 1) {
            qrcodeUrl = res.paperBaseInfo.qrCodeUrl
          } else if (res.redirectTo == 2) {
            qrcodeUrl = res.paperBaseInfo.homeQrcode;
          } else if (res.redirectTo == 3) {
            qrcodeUrl = res.customizeQrCode.img;
          }
          qrCodeText = res.qrCodeText ? res.qrCodeText : qrCodeText
          if (qrcodeUrl.includes("?")) {
            qrcodeUrl = qrcodeUrl + "&time=" + new Date().getTime();
          } else {
            qrcodeUrl = qrcodeUrl + "?time=" + new Date().getTime();
          }
          $this.spreadInfo = {
            qrCodeText:qrCodeText,
            scoringMethod: res.paperBaseInfo.scoringMethod,
            bgImgUrl: res.image,
            headimgurl: res.headimgurl,
            certificateName: res.name,
            nickname: res.nickname,
            realName:res.realName,
            name: titleArr,
            qrcodeUrl: qrcodeUrl,
            word: res.content || [],
            contentType:res.contentType,
            enableShowQrCode:res.enableShowQrCode,
            accuracy: res.paperBaseInfo.scoringMethod == 1 ? res.paperBaseInfo.accuracy : (res.paperBaseInfo.scoringMethod == 2 ? res.paperBaseInfo.totalpoins : res.paperBaseInfo.rightNum),
            title:res.title,
            enableInstitution:res.enableInstitution, //是否展示发证机构：1=展示；0=隐藏
            institutionName:res.institutionName, //机构名称
            enableGrantTime:res.enableGrantTime, //是否展示发证时间  1=展示；0=隐藏
            enableNumber:res.enableNumber, //是否展示证书编号 1=展示；0=隐藏
            number:res.number, //起始编号
            enableStamp:res.enableStamp, //是否展示章戳  1=展示；2=自定义; 0=隐藏
            stampImg:res.stampImg, //章戳自定义图片
            wordArr:[],
            createdAt:res.createdAt
          };
          if (res.contentType == 1) {
            let defaultWord = $this.spreadInfo.word[0];
            let firstLine = defaultWord.substring(0, 8);
            let secendLine = defaultWord.substring(8, 26);
            let thirdLine = defaultWord.substring(26, 44);
            firstLine && $this.spreadInfo.wordArr.push(
              firstLine
            );
            secendLine && $this.spreadInfo.wordArr.push(
              secendLine
            );
            thirdLine && $this.spreadInfo.wordArr.push(
              thirdLine
            );
          } else {
            $this.spreadInfo.wordArr = $this.spreadInfo.word;
          }
          // $this.startCanvas();
        }
        document.ontouchstart = null;
        document.ontuchmove = null;
        document.ontouchend = null;
        $this.$nextTick(() => {
          $this.canvas();
        });
      }, failRes => {
        $this.$loading.hide();
        $this.isDrawing = false;
      });
    },
    startCanvas() {
      let that = this;
      let canvas = document.createElement("canvas");
      canvas.width = CANVAS_WIDTH;
      canvas.height = CANVAS_HEIGHT;
      let ctx = canvas.getContext("2d");

      //开始绘制图片
      let bgImgurl = this.spreadInfo.bgImgUrl;
      this.downImg(bgImgurl)
        .then(bgImg => {
          //绘制最外层背景图片
          ctx.save();
          ctx.drawImage(bgImg, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
          bgImg = null;
          if (that.matchPaper.nameTypeShow != 0) {
          //绘制昵称
          for (let i = 0; i < that.spreadInfo.nickname.length; i++) {
            //绘制昵称文字
            let itemText = {
              fontSize: 26,
              fontColor: "#333333",
              textAlign: "center",
              textStr: that.spreadInfo.nickname,
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 460
            };
            that.drawText(ctx, itemText);
          }}
          //绘制标题
          for (let i = 0; i < that.spreadInfo.name.length; i++) {
            //绘制简介文字
            let itemText = {
              fontSize: 30,
              fontColor: "#333333",
              textAlign: "center",
              textStr: that.spreadInfo.name[i],
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 539 + i * 43
            };
            that.drawText(ctx, itemText);
          }
          // enableShowAccuracy: 1
          // enableShowRightNum: 1
          // enableShowScore: 1
          if (that.matchPaper.defineShowContent.includes(6) &&
            !that.matchPaper.defineShowContent.includes(5) &&
            !that.matchPaper.defineShowContent.includes(7)) {
            let accuracyText = {
              fontSize: 50,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: Number(that.matchPaper.paperBaseInfo.accuracy * 100).toFixed(0) + '%',
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 657
            };
            that.drawText(ctx, accuracyText);
            let percentText = {
              fontSize: 30,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: '正确率',
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 720
            };
            that.drawText(ctx, percentText);
          }
          if (!that.matchPaper.defineShowContent.includes(6) &&
            !that.matchPaper.defineShowContent.includes(5) &&
            that.matchPaper.defineShowContent.includes(7)) {
            let accuracyText = {
              fontSize: 50,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: that.matchPaper.paperBaseInfo.rightNum,
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 657
            };
            that.drawText(ctx, accuracyText);
            let percentText = {
              fontSize: 30,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: '正确数',
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 720
            };
            that.drawText(ctx, percentText);
          }
          if (!that.matchPaper.defineShowContent.includes(6) &&
            that.matchPaper.defineShowContent.includes(5) &&
            !that.matchPaper.defineShowContent.includes(7)) {
            let accuracyText = {
              fontSize: 50,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: that.matchPaper.paperBaseInfo.totalpoins,
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 657
            };
            that.drawText(ctx, accuracyText);
            let percentText = {
              fontSize: 30,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: '总分',
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 720
            };
            that.drawText(ctx, percentText);
          }
          //两个选中的情况
          if ((that.matchPaper.defineShowContent.includes(6) &&
            that.matchPaper.defineShowContent.includes(5) &&
            !that.matchPaper.defineShowContent.includes(7)) ||
            (!that.matchPaper.defineShowContent.includes(6) &&
            that.matchPaper.defineShowContent.includes(5) &&
            that.matchPaper.defineShowContent.includes(7)) ||
            (that.matchPaper.defineShowContent.includes(6) &&
            !that.matchPaper.defineShowContent.includes(5) &&
            that.matchPaper.defineShowContent.includes(7))
          ) {
            let accuracyText = {
              fontSize: 50,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr:  that.matchPaper.defineShowContent.includes(5) ?
              that.matchPaper.paperBaseInfo.totalpoins : that.matchPaper.defineShowContent.includes(6) ?
              Number(that.matchPaper.paperBaseInfo.accuracy * 100).toFixed(0) + '%' : '',
              offsetX: CANVAS_WIDTH / 3,
              offsetY: 657
            };
            that.drawText(ctx, accuracyText);
            let percentText = {
              fontSize: 30,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: that.matchPaper.defineShowContent.includes(5) ?
              '总分' : that.matchPaper.defineShowContent.includes(6) ? '正确率' : '',
              offsetX: CANVAS_WIDTH / 3,
              offsetY: 720
            };
            that.drawText(ctx, percentText);
            let accuracyTextsec = {
              fontSize: 50,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: that.matchPaper.defineShowContent.includes(7) ? that.matchPaper.paperBaseInfo.rightNum :
              that.matchPaper.defineShowContent.includes(6) ? Number(that.matchPaper.paperBaseInfo.accuracy * 100).toFixed(0) + '%' : '',
              offsetX: CANVAS_WIDTH / 1.5,
              offsetY: 657
            };
            that.drawText(ctx, accuracyTextsec);
            let percentTextsec = {
              fontSize: 30,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: that.matchPaper.defineShowContent.includes(7) ? '正确数' :
              that.matchPaper.defineShowContent.includes(6) ? '正确率' : '',
              offsetX: CANVAS_WIDTH / 1.5,
              offsetY: 720
            };
            that.drawText(ctx, percentTextsec);
          }
          if (that.matchPaper.defineShowContent.includes(5) && that.matchPaper.defineShowContent.includes(6) && that.matchPaper.defineShowContent.includes(7)
          ) {
            let accuracyText = {
              fontSize: 50,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: that.matchPaper.paperBaseInfo.totalpoins,
              offsetX: CANVAS_WIDTH / 8 * 2,
              offsetY: 657
            };
            that.drawText(ctx, accuracyText);
            let percentText = {
              fontSize: 30,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: '总分',
              offsetX: CANVAS_WIDTH / 8 * 2,
              offsetY: 720
            };
            that.drawText(ctx, percentText);
            let accuracyTextsec = {
              fontSize: 50,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: Number(that.matchPaper.paperBaseInfo.accuracy * 100).toFixed(0) + '%',
              offsetX: CANVAS_WIDTH / 8 * 4,
              offsetY: 657
            };
            that.drawText(ctx, accuracyTextsec);
            let percentTextsec = {
              fontSize: 30,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: '正确率',
              offsetX: CANVAS_WIDTH / 8 * 4,
              offsetY: 720
            };
            that.drawText(ctx, percentTextsec);
            let accuracyTextthrid = {
              fontSize: 50,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: that.matchPaper.paperBaseInfo.rightNum,
              offsetX: CANVAS_WIDTH / 8 * 6,
              offsetY: 657
            };
            that.drawText(ctx, accuracyTextthrid);
            let percentTextthrid = {
              fontSize: 30,
              fontColor: "#C87F1B",
              textAlign: "center",
              textStr: '正确数',
              offsetX: CANVAS_WIDTH / 8 * 6,
              offsetY: 720
            };
            that.drawText(ctx, percentTextthrid);
          }
          //绘制说明
          let wordArr = [];
          if (that.spreadInfo.contentType == 1) {
            let defaultWord = that.spreadInfo.word[0];
            let firstLine = defaultWord.substring(0, 8);
            let secendLine = defaultWord.substring(8, 26);
            let thirdLine = defaultWord.substring(26, 44);
            firstLine && wordArr.push(
              firstLine
            );
            secendLine && wordArr.push(
              secendLine
            );
            thirdLine && wordArr.push(
              thirdLine
            );
          } else {
            wordArr = that.spreadInfo.word;
          }
          for (let i = 0; i < wordArr.length; i++) {
            let pingyuText = {
              fontSize: 24,
              fontColor: "#666666",
              textAlign: "center",
              textStr: wordArr[i],
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 810 + i * 40
            };
            that.drawText(ctx, pingyuText);
          }
          if (that.spreadInfo.enableShowQrCode == 1) {
            //绘制长按识别文字
            let tipText = {
              fontSize: 24,
              fontColor: "#999",
              textAlign: "center",
              textStr: that.spreadInfo.qrCodeText,
              offsetX: CANVAS_WIDTH / 2,
              offsetY: 1194
            };
            that.drawText(ctx, tipText);
          }
          if (that.spreadInfo.headimgurl == null || that.spreadInfo.headimgurl == '') {
            return that.downImg(
              require("../../../assets/defult_head.png")
            );
          } else {
            return that.downImg(that.spreadInfo.headimgurl);
          }
        })
        .then(headimgurl => {
          //绘制圆形头像
          if (that.matchPaper.enableAvatarShow == 1) {
          ctx.save();
          //        ctx.beginPath();
          //        ctx.arc(321, 152, 48, 0, 2 * Math.PI);
          //        ctx.clip();
          //        ctx.fillStyle = "#ffffff";
          //        ctx.fill();
          //        ctx.restore();
          //        ctx.save();
          ctx.beginPath();
          ctx.arc(370, 390, 50, 0, 2 * Math.PI);
          ctx.clip();
          ctx.drawImage(headimgurl, 320, 340, 100, 100);
          ctx.restore();
          headimgurl = null;}
          if (that.spreadInfo.enableShowQrCode == 1) {
            return that.downImg(that.spreadInfo.qrcodeUrl);
          } else {
            that.canvasToImage(ctx);
          }
        })
        .then(qrCodeImg => {
          //绘制二维码
          if (that.spreadInfo.enableShowQrCode == 1) {
            ctx.drawImage(qrCodeImg, 284, 986, 180, 180);
          }
          qrCodeImg = null;
          that.canvasToImage(ctx);
        });
    },
    //下载图片
    downImg(imgUrl) {
      let that = this;
      return new Promise(function (resolve, reject) {
        let img = new Image();
        if (!imgUrl.includes('base64')) {
          img.crossOrigin = "anonymous";
          let nowTimeTmp = Date.now();
          imgUrl = imgUrl.includes('?') ? `${imgUrl}&time=${nowTimeTmp}` : `${imgUrl}?time=${nowTimeTmp}`;
        }
        img.src = imgUrl;
        img.onload = function () {
          resolve(img);
        };
        img.onerror = function (e) {
          console.log("下载图片失败");
          console.log(imgUrl);
          that.isDrawing = false;
          reject(e);
        };
      });
    },

    //绘制文字
    drawText(ctx, fontInfo) {
      ctx.font = fontInfo.fontSize + "px Microsoft YaHei";
      ctx.fillStyle = fontInfo.fontColor;
      ctx.textBaseline = "top";
      ctx.textAlign = fontInfo.textAlign;
      ctx.fillText(fontInfo.textStr, fontInfo.offsetX, fontInfo.offsetY, 600);
    },
    showCerImage(dataURL) {
      let ig = document.getElementById("spreadClockImg");
      ig.setAttribute("src", dataURL);
      this.showCer = true;
    },
    //将canvas转成图片
    canvasToImage(ctx) {
      try {
        let quality = 1
        let dataURL, blob
        do {
        dataURL = ctx.canvas.toDataURL('image/jpeg', quality)
        blob = this.dataURItoBlob(dataURL)
          if (quality > 0.1) {
            quality -= 0.01
          } else {
            quality -= 0.015
          }
        } while (dataURL.size > 5242880 && quality > 0.07)
        let ig = document.getElementById("spreadClockImg");
        this.$nextTick(() => {
          this.$loading.hide();
          ig.setAttribute("src", dataURL);
        });
        if (this.testRes && this.testRes.isMatch == 2) {
          this.receiveCard(blob);
        } else if ((this.testRes && this.testRes.isMatch == 3) || !this.testRes) {
          this.updateCardImage(blob)
          this.isDrawing = false;
        }
      } catch (err) {
        this.isDrawing = false;
        this.$loading.hide();
      }
    },
    updateCardImage(blob) {
      let that = this;
      let blobDate = []
      blob.name = that.prodId
      blobDate.push(blob)
      utilJs.imgUpload(blobDate, imgData, 'exam', res => {
        let image = res
        utilJs.postMethod(global.apiurl + 'Certificate/updateCardImage', {
          type:that.bigType,
          prodType:that.prodType,
          prodId:that.prodId,
          image:image
        }, function () {
          that.$emit('updateImgeUrl', image);
        });
      });
    },
    receiveCard(BlobFile) {
      let that = this;
      // let fd = new FormData();
      // fd.append('avatar', BlobFile);
      // let xhr = new XMLHttpRequest()
      // xhr.onreadystatechange = function () {
        // if (this.readyState == 4 && this.status == 200) {
        that.isDrawing = false;
        utilJs.postMethod(global.apiurl + 'Certificate/receiveCard', {
          prodType:that.prodType,
          prodId:that.prodId,
          fromTopicld:that.topicId,
          type:that.bigType,
        }, function (res) {
          that.testRes.isMatch = 3;
          that.updateCardImage(BlobFile)
        });
        // } else {
        //   if (this.readyState == 4) {
        //     that.isDrawing = false;
        //   }
        // }
      // }
      // xhr.open('POST', global.apiurl + 'admin/common/examCertificate/imageUpload', true)
      // xhr.send(fd)
    },
    dataURItoBlob(base64Data) {
      var byteString;
      if (base64Data.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(base64Data.split(',')[1]);
      } else {
        byteString = unescape(base64Data.split(',')[1]);
      }
      var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
      var ia = new Uint8Array(byteString.length);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ia], { type: mimeString});
    },
  },
};
</script>

<style scoped>
.canvasBox {
  width: 750px;
  height: 1334px;
  top: -999999999px;
  left: -30000000px;
  z-index: -999;
  position: absolute;
}
.anvasContent {
  width: 750px;
  height: 1334px;
  position: relative;
}
.bgLocation {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}
.canvasBoxhor {
  width: 750px;
  height: 530px;
  top: -999999999px;
  left: -30000000px;
  z-index: -999;
  position: absolute;
}
.anvasContenthor {
  width: 750px;
  height: 530px;
  position: relative;
}
.shapecanvasBoxhor {
  width: 1060px;
  height: 750px;
  top: -999999999px;
  left: -30000000px;
  z-index: -999;
  position: absolute;
}
.shapeanvasContenthor{
  width: 1060px;
  height: 750px;
  position: relative;
}
</style>
